"""
CREATE: 2018/5/16
AUTHOR:　HEHAHUTU
"""
from flask_restful import Resource, reqparse
from app.api import api
from flask_login import login_required
from f_lib.code import Msg
from app.models.task.mi import MiTask
from f_lib.principal.safety import safety_strategy


class TaskOperation(Resource):

    def get(self):
        return Msg.success('success')


class MiTaskOption(Resource):
    gparse = reqparse.RequestParser()
    gparse.add_argument('task_name', type=str, required=True)
    pparse = reqparse.RequestParser()
    pparse.add_argument('task_name', type=str, required=True)
    pparse.add_argument('cookies', type=str)
    pparse.add_argument('run_time', type=int)

    @safety_strategy
    def get(self):
        arg = self.gparse.parse_args()
        mis = MiTask.query_one(**arg)
        if mis:
            return Msg.success(cookies=mis.cookies, run_time=mis.run_time)
        return Msg.failed('任务不存在')

    @safety_strategy
    def post(self):
        arg = self.pparse.parse_args()
        mis = MiTask.query_one(task_name=arg['task_name'])
        if mis:
            mis.update(**arg)
            return Msg.success('update success')
        else:
            MiTask.create(**arg)
            return Msg.success('add success')


api.add_resource(TaskOperation, '/task', endpoint='task')
api.add_resource(MiTaskOption, '/task/mi')
